package com.tcpengine.net;

import com.tcpengine.client.LogView;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

// tcp 客户端
public class TcpClient {
	private LogView m_logView = null;
	private ChannelFuture m_chFuture = null;
	
	public TcpClient(LogView logView) {
		m_logView = logView;
	}
	
	// tcp 连接服务端
	public void tcpConnect(String strUrl) {
		 m_logView.println("连接tcp客户端：" + strUrl);
        String[] arrNetAddr = strUrl.split(":");
        if(arrNetAddr.length < 2) {
        	m_logView.println("tcp网络地址格式不合法");
        	return;
        }
        int tcpPort = Integer.parseInt(arrNetAddr[1]);
		
        Bootstrap clientBootstap = new Bootstrap();
        EventLoopGroup worker = new NioEventLoopGroup();
        clientBootstap.group(worker);
        clientBootstap.channel(NioSocketChannel.class);

        //5.添加Handler
        clientBootstap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                // pipeline.addLast("StringDecoder",new StringDecoder());
                // pipeline.addLast("StringEncoder",new StringEncoder());
                pipeline.addLast("ClientHandler",new TcpHandler(m_logView));
            }
        });

        m_chFuture = clientBootstap.connect(arrNetAddr[0],tcpPort);
        
//        try {
//            //7.测试输入
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//            while(true){
//                System.out.println("请输入：");
//                String msg = bufferedReader.readLine();
//                channelFuture.channel().writeAndFlush(msg);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            //8.关闭连接
//            worker.shutdownGracefully();
//        }
		
	}
	
	public void sendMessage(Msg msg) {
		// BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Encoder.encode(msg));
		ByteBuf byteBuf = Encoder.encode(msg);
		m_chFuture.channel().writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    m_logView.println("tcp发送消息成功");
                } else {
                	m_logView.println("tcp消息发送失败 " + channelFuture.cause().getMessage());
                }
            }
        });
		
	}
	
}
